<script setup>
import { ref,getCurrentInstance } from 'vue'
import { Plus } from "@element-plus/icons-vue";
import { onMounted } from "vue";
import { userPageService } from "@/api/user.js";
import { matchSelectService } from "@/api/match.js";
import { teacherSelectService } from "@/api/teacher.js";
import { fileDownloadService } from "@/api/file.js";
import { ElMessage, ElMessageBox } from "element-plus";
import axios from "@/utils/request.js";
import { trainDeleteService, trainModifyService } from "@/api/train.js";
import { certificateDeleteService, certificateSelectService, certificateUploadService } from "@/api/certificate.js";
import moment from 'moment';

//获取全局变量
const instance = getCurrentInstance();  // 获取当前实例
const $imageUrlPre = instance.appContext.config.globalProperties.$imageUrlPre;


/**
 * 上传证书
 */
//定义校验规则
const certificateFormRef = ref()
const certificateRules = {
  certificateName: [
    { required: true, message: '证书名称不能为空', trigger: 'blur' },
    { max: 30, message: '证书名称不能超过30个字', trigger: 'blur' }
  ],
  list: [
    { required: true, message: '所属队员不能为空', trigger: 'change' }
  ],
  matchId: [
    { required: true, message: '关联比赛不能为空', trigger: 'change' }
  ],
  'teacherInfo.teacherName': [
    { required: true, message: '指导老师不能为空', trigger: 'change' }
  ],
  filePath: [
    { required: true, message: '证书图片不能为空', trigger: 'change' }
  ],
  getTime: [
    { required: true, message: '获得时间不能为空', trigger: 'change' }
  ],
}
//根据条件获取所有队员信息
const userList = ref([])
const loading = ref(false)
const handleInputChange = (query) => {
  loading.value = true;
  setTimeout(() => {
    loadUser(query)
    loading.value = false;
  }, 500);
}
const loadUser = async (name) => {
  const res = await userPageService(1, 100000, '', name, '')
  userList.value = res.data.data.list
}
//  根据条件获取所有比赛信息
const matchList = ref([])
const matchLoading = ref(false)
const handleInputMatchChange = (query) => {
  matchLoading.value = true;
  setTimeout(() => {
    loadMatch(query)
    matchLoading.value = false;
  }, 1000);
}
const loadMatch = async (name) => {
  const res = await matchSelectService(1, 100000, name, '')
  matchList.value = res.data.data.list
}
//  根据条件获取所有老师信息
const teacherList = ref([])
const currentTeacherName = ref()
const teacherLoading = ref(false)
const handleInputTeacherChange = (query) => {
  teacherLoading.value = true;
  setTimeout(() => {
    loadTeacher(query)
    teacherLoading.value = false;
  }, 1000);
}
const loadTeacher = async (name) => {
  const res = await teacherSelectService(1, 100000, name)
  teacherList.value = res.data.data.list
}
const changeTeacher = (teacherInfo) => {
  if (!teacherInfo) return
  certificateForm.value.teacherInfo = teacherInfo
}


const fileList = ref([])
const showUploadCertificate = ref(false)
const certificateForm = ref({
  certificateName: '',
  type: 1,
  list: '',
  matchId: '',
  teacherInfo: {
    teacherId: '',
    teacherName: '',
  },
  getTime: '',
  filePath: ''
})
//文件上传成功处理逻辑
const handleFileUpload = (res, file, fileList) => {
  // fileList.value = fileList
  //将后端返回的文件url赋值给表单中的filePath属性
  certificateForm.value.filePath = res.data
}
const handleRemove = () => {
  certificateForm.value.filePath = ''
}
const getToken = () => {
  return localStorage.getItem('token') || {}
}
const beforeCertificateUpload = (rawFile) => {
  if (!rawFile.type.startsWith('image/')) {
    ElMessage.error('上传文件必须是图片!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error('上传图片不能超过 10MB!')
    return false
  }
  return true
}
//格式化日期并渲染在表格上
const formatDate = (dateString) => {
  const date = new Date(dateString);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以需要加1
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}
//校验规则并发送添加证书请求
const addCertificate = async (formEl) => {
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (valid) {
      if (!Array.isArray(certificateForm.value.list)) {
        certificateForm.value.list = [certificateForm.value.list];  // 转换为数组
      }
      // 解构 certificateForm.value 中的嵌套属性
      const {
        teacherInfo: { teacherId, teacherName }
      } = certificateForm.value;
      certificateForm.value.teacherId = teacherId
      certificateForm.value.teacherName = teacherName
      certificateForm.value.getTime = moment(certificateForm.value.getTime).format("YYYY-MM-DD HH:mm:ss");
      const res = await certificateUploadService(certificateForm.value)
      if (res.data.status === 'success') {
        ElMessage.success('上传成功')
        certificateForm.value.certificateName = ''
        certificateForm.value.type = 1
        certificateForm.value.list = []
        certificateForm.value.matchId = ''
        certificateForm.value.teacherInfo = {
          teacherId: '',
          teacherName: '',
        },
        certificateForm.value.getTime = ''
        certificateForm.value.filePath = ''
        currentTeacherName.value = ''
        fileList.value = []
        showUploadCertificate.value = false
        certificateFormRef.value.resetFields()
        await load()

      } else {
        ElMessage.error(res.data.info)
      }
    }
  })
}
/**
 * 分页查询证书
 */
//分页查询底部导航栏和搜索框变量
const certificateInfo = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const certificateNameInput = ref('')
const userNameInput = ref('')
const total = ref(0)
const selectIds = Array
const handleSelectionChange = (selection) => {
  selectIds.value = selection.map(item => item.certificateId)
}
const handleCurrentChange = (val) => {
  currentPage.value = val
  load()
}
const handleSizeChange = (val) => {
  pageSize.value = val
  load()
}
onMounted(() => {
  load()
})
//初始化图片数组变量，用于图片预览
const users = ref([])
const matches = ref([])
const imageUrlList = ref([])
const load = async () => {
  //查询队员信息
  const res1 = await userPageService(1,100000,'','','')
  users.value = res1.data.data.list
  //查询比赛信息
  const res2 = await matchSelectService(1,100000,'','')
  matches.value = res2.data.data.list
  const res = await certificateSelectService(currentPage.value, pageSize.value, certificateNameInput.value, userNameInput.value)
  if (res.data.status === 'success') {
    certificateInfo.value = res.data.data.list
    // 批量下载图片，并更新 imageUrlList
    const filePaths = certificateInfo.value.map(v => v.filePath);
    // 使用 map 方法生成完整的 URL 数组
    const imageUrls = filePaths.map(filePath => $imageUrlPre + filePath);
    //  const imageUrls = filePaths.map(filePath => URL.createObjectURL(new Blob([fileDownloadService(filePath).data])));
    // 更新 certificateInfo 中的 filePath 为图片的 URL
    certificateInfo.value.forEach((item, index) => {
      item.imageFilePath = imageUrls[index] || ''; // 如果失败则为空字符串
      //更新所属队员和关联比赛
      item.userName = users.value.find(user => String(user.userId) == String(item.userId))?.name || "未知用户";
      item.matchName = matches.value.find(match => match.matchId == item.matchId)?.matchName || '未知比赛';
    });
    total.value = res.data.data.totalCount
    // imageUrlList.value = certificateInfo.value.map(v => v.filePath)
    imageUrlList.value = imageUrls
  } else {
    ElMessage.error('系统错误')
  }
}
/**
 * 
 * @param certificateId 下载证书
 */
const downloadCertificate = async (certificate) => {
  const res = await fileDownloadService(certificate.filePath)
  if (res.status === 200) {
    // 创建Blob对象
    const file = new Blob([res.data], { type: res.data.type });
    console.log(res.data.type)
    // 创建URL对象
    const fileURL = URL.createObjectURL(file);
    // 创建一个隐藏的a标签并设置属性
    const link = document.createElement('a');
    link.href = fileURL;
    link.setAttribute('download', certificate.certificateName + '.jpg'); // 设置下载文件名
    document.body.appendChild(link);
    link.click(); // 触发下载
    document.body.removeChild(link); // 清理DOM
    URL.revokeObjectURL(fileURL); // 释放URL对象
    await ElMessage.success('下载证书成功')
  } else {
    ElMessage.error(res.info)
  }
}
/**
 * 根据证书id删除证书
 */
const deleteCertificate = async (certificateId) => {
  const certificateIds = Array.of(certificateId)
  ElMessageBox.confirm(
    '确定要删除该证书信息吗?',
    '警告',
    {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      const res = await certificateDeleteService(certificateIds)
      if (res.data.status === 'success') {
        ElMessage.success('删除成功')
        await load()
      } else {
        ElMessage.error(res.data.info)
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}
const deleteCertificates = async () => {
  //非空判断
  if (selectIds.value == null) {
    ElMessage.info('未选中任何一个证书')
    return
  }
  if (selectIds.value != null && selectIds.value.length === 0) {
    ElMessage.info('未选中任何一个证书')
    return
  }
  ElMessageBox.confirm(
    '确定要删除所有选中的证书信息吗?',
    '警告',
    {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      const res = await certificateDeleteService(selectIds.value)
      if (res.data.status === 'success') {
        ElMessage.success('删除成功')
        await load()
      } else {
        ElMessage.error(res.data.info)
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}
</script>

<template>
  <!--  上传证书模态窗口-->
  <el-dialog v-model="showUploadCertificate" title="上传证书" width="650" style="top: -50px">
    <el-form ref="certificateFormRef" :rules="certificateRules" :model="certificateForm">
      <el-form-item prop="certificateName" label="证书名称">
        <el-input v-model="certificateForm.certificateName" style="width: 400px" autocomplete="off" />
      </el-form-item>
      <el-form-item label="证书类型" style="margin-left: 10px;">
        <el-radio-group v-model="certificateForm.type">
          <el-radio :value="1">个人</el-radio>
          <el-radio :value="2">团体</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item prop="list" label="所属队员" :label-width="80">
        <el-select v-model="certificateForm.list" clearable placeholder="请查找并选择证书归属队员" style="width: 240px" filterable
          :multiple="certificateForm.type == 2" :remote-method="handleInputChange" :remote="true" :loading="loading">
          <el-option v-for="(item, index) in userList" :key="index" :label="item.name" :value="item.userId" />
        </el-select>
      </el-form-item>
      <el-form-item prop="matchId" label="关联比赛" :label-width="80">
        <el-select v-model="certificateForm.matchId" clearable placeholder="请查找并选择证书关联比赛" style="width: 240px"
          filterable :remote="true" :remote-method="handleInputMatchChange" :loading="matchLoading">
          <el-option v-for="(item, index) in matchList" :key="index" :label="item.matchName" :value="item.matchId" />
        </el-select>
      </el-form-item>
      <el-form-item label="指导老师" prop="teacherInfo.teacherName" :label-width="80">
          <el-select v-model="certificateForm.teacherInfo.teacherName" clearable placeholder="请查找并选择指导老师" style="width: 240px" filterable
            :remote="true" :remote-method="handleInputTeacherChange" @change="changeTeacher" :loading="teacherLoading">
            <el-option v-for="(item, index) in teacherList" :key="index" :label="item.teacherName" :value="item" />
          </el-select>
        </el-form-item>
      <el-form-item prop="filePath" label="证书图片">
        <el-upload :headers="{ token: getToken() }" :action="axios.defaults.baseURL + '/certificateInfo/uploadImage'"
          :on-success="handleFileUpload" :on-remove="handleRemove" list-type="picture" limit="1"
          :before-upload="beforeCertificateUpload" :file-list="fileList">
          <el-button type="primary" style="margin-left: 100px">点击上传</el-button>
        </el-upload>
      </el-form-item>
      <el-form-item prop="getTime" label="获得时间">
        <div class="demo-datetime-picker">
          <div class="block">
            <el-date-picker v-model="certificateForm.getTime" type="datetime" placeholder="填写证书获得日期（可选）"
              format="YYYY-MM-DD HH:mm:ss" date-format="MMM DD, YYYY" time-format="HH:mm" />
          </div>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="showUploadCertificate = false">取消</el-button>
        <el-button type="primary" @click="addCertificate(certificateFormRef)">
          添加
        </el-button>
      </div>
    </template>
  </el-dialog>
  <div>
    <!--      功能栏-->
    <el-card style="float: left;margin-bottom: 20px">
      <el-button type="primary" @click="showUploadCertificate = true" round>上传证书</el-button>
      <el-button type="danger" @click="deleteCertificates" round>批量删除</el-button>
    </el-card>
    <!--      搜索栏-->
    <el-card class="certificate-search">
      <span>
        <h2>证书名称：</h2>
      </span>
      <input v-model="certificateNameInput" @keyup.enter.native="load">
      <span style="margin-left: 10px">
        <h2>比赛名称：</h2>
      </span>
      <input v-model="matchNameInput" @keyup.enter.native="load">
      <span style="margin-left: 10px">
        <h2>队员姓名：</h2>
      </span>
      <input v-model="userNameInput" @keyup.enter.native="load">
      <el-button type="warning" @click="load">搜索</el-button>
    </el-card>
  </div>
  <!--      表格-->
  <el-table ref="multipleTableRef" :data="certificateInfo" stripe class="table-style"
    style="width: 100%;margin-top: 30px;align: center" @selection-change="handleSelectionChange">
    <el-table-column type="selection" width="35" />
    <el-table-column property="certificateId" label="编号" width="70" />
    <el-table-column style="z-index: 100" property="certificateName" label="证书名称" width="150">
    </el-table-column>
    <el-table-column style="z-index: 100" property="type" label="证书类型" width="100">
      <template #default="scope">
        <div v-if="scope.row.type === 1">个人</div>
        <div v-if="scope.row.type === 2">团队</div>
      </template>
    </el-table-column>
    <el-table-column property="userName" label="所属队员" width="130">
    </el-table-column>
    <el-table-column property="matchName" label="关联比赛" width="130">
    </el-table-column>
    <el-table-column property="teacherName" label="指导老师" width="120">
    </el-table-column>
    <el-table-column property="filePath" label="证书" width="130">
      <template #default="scope">
        <el-image style="width: 70px;height: 70px" fit="cover" preview-teleported :preview-src-list="imageUrlList"
          :initial-index="scope.$index" :src="scope.row.imageFilePath" alt="证书图片" />
      </template>
    </el-table-column>
    <el-table-column property="getTime" label="获取时间" width="130">
      <template #default="scope">
        {{ formatDate(scope.row.getTime) }}
      </template>
    </el-table-column>
    <el-table-column property="createTime" label="创建时间" width="170" />
    <el-table-column label="操作">
      <template #default="scope">
        <el-button size="small" type="success" @click="downloadCertificate(scope.row)">
          下载
        </el-button>
        <el-button size="small" type="danger" @click="deleteCertificate(scope.row.certificateId)">
          删除
        </el-button>
      </template>
    </el-table-column>
  </el-table>
  <!--    分页组件-->
  <el-card style="margin-top: 20px;float: right;">
    <div class="demo-pagination-block">
      <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[2, 5, 10, 20]"
        size="large" :background="true" layout="total, sizes, prev, pager, next, jumper" :total="total"
        @current-change="handleCurrentChange" @size-change="handleSizeChange" />
    </div>
  </el-card>
</template>

<style scoped>
/*搜索框样式*/
.certificate-search {
  width: 1000px;
  float: left;
  margin-left: 20px;
}

.certificate-search span {
  float: left;
}

.certificate-search input {
  float: left;
  height: 25px;
  border: solid 2px;
  margin-top: 2px;
}

/*上传证书图片样式*/
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader .avatar-uploader-icon {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .avatar-uploader-icon:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

/*上传证书图片样式*/
/*图片预览样式*/
.demo-image__error .image-slot {
  font-size: 30px;
}

.demo-image__error .image-slot .el-icon {
  font-size: 30px;
}

.demo-image__error .el-image {
  width: 100%;
  height: 200px;
}

/*图片预览样式*/
:deep() th.el-table__cell {
  color: black;
  font-size: 18px;
}
</style>
